#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from documents.itemtype import ItemType

class ItemTypeField(models.Field):
    """
    Creates an abstraction from the ItemType and is capable of storing
    it in the DB (as the name of the associated Model)
    """
    
    description = 'An item-type'
    
    __metaclass__ = models.SubfieldBase
    
    def __init__(self, *args, **kwargs):
        super(ItemTypeField, self).__init__(*args, **kwargs)
    
    def get_internal_type(self):
        return "TextField"
    
    def to_python(self, value):
        if isinstance(value, ItemType):
            return value
        
        # String case
        return ItemType.get_item_type_for_identifier(value)
    
    def get_prep_value(self, value):
        return value.identifier